package com.topcheer.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.topcheer.gateway.common.JacksonUtils;
import com.topcheer.gateway.common.ResultVo;
import com.topcheer.gateway.common.properties.Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author xutao
 * @Package com.topcheer.gateway.filter
 * @Description: ${todo}
 * @date 2020/1/2 17:22
 */
@Slf4j
public class BlackListFilter implements GatewayFilter, Ordered {

    private String[] paths;

    public BlackListFilter(String[] paths) {
        this.paths = paths;
    }
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getURI().getPath().trim();
        for(String blackListPath:paths){
            if(path.contains(blackListPath)){
                ResultVo resultVo = ResultVo.builder().code(HttpStatus.UNAUTHORIZED.value()).msg(HttpStatus.UNAUTHORIZED.getReasonPhrase()).build();
                byte[] bytes;
                try {
                    bytes = JacksonUtils.write(resultVo).getBytes();
                } catch (JsonProcessingException e) {
                    log.error("com.topcheer.gateway.filter.BlackListFilter.filter error | ",e);
                    bytes = "{\"code\":401,\"msg\":\"Unauthorized\"}".getBytes();
                }
                DataBuffer wrap = exchange.getResponse().bufferFactory().wrap(bytes);
                return exchange.getResponse().writeWith(Flux.just(wrap));
            }
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
